package com.pactera.madp.cp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.pactera.madp.cp.api.dto.track.BehaviorTrackDto;
import com.pactera.madp.cp.service.BehaviorTrackService;
import com.pactera.madp.cp.service.ICorpService;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

@Service
@AllArgsConstructor
public class BehaviorTrackServiceImpl implements BehaviorTrackService{

    private IWorkEmployeeService workEmployeeService;
    private IWorkContactService workContactService;
    private ICorpService corpService;

    @Override
    public void handleTrack(BehaviorTrackDto dto, HttpServletResponse response) throws Exception{

        //获取事件处理对象
        String event = dto.getEvent();
        BaseBehaviorTrackServer behaviorTrackServer = BaseBehaviorTrackServer.selectHandler(event);

        //解码
        String title = dto.getTitle();
        String url = dto.getUrl();
        String content = dto.getContent();
        title = StringUtils.isEmpty(title) ? title : URLDecoder.decode(title);
        url = StringUtils.isEmpty(url) ? url : URLDecoder.decode(url);
        content = StrUtil.isEmpty(content) ? content : URLDecoder.decode(content);
        dto.setTitle(title);
        dto.setUrl(url);
        dto.setContent(content);
        dto.setTenantId(corpService.list().get(0).getTenantId());

        //事件处理
        behaviorTrackServer.handleEvent(dto, workEmployeeService, workContactService, response);
    }
}
